/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package smsserver.manager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import smscommon.Global;
import smsserver.utils.DES2;

/**
 *
 * @author ZHENG ZHI YOU
 */
public class FileSystemManager {
    static String filedir = "iccid//";
    static FileSystemManager fsm = null;
    public static FileSystemManager getIntance()
    {
        if(fsm==null)
        {
            fsm = new FileSystemManager();
            File file = new File(filedir);
            if(!file.exists())
            {
                file.mkdir();
            }else{
                if(!file.isDirectory())
                {
                    file.delete();
                    file.mkdir();
                }
            }
        }

        return fsm;
    }
    public String getContent(String iccid)
    {
        String content = "";
        String filename = iccid+".txt";
        File file = new File("iccid//"+filename);
        if(!file.exists()||file.isDirectory())
        {
            return content;
        }

        try{
            BufferedReader br = new BufferedReader(new FileReader(file));
            String temp=null;
            StringBuffer sb=new StringBuffer();
            temp=br.readLine();
            while(temp!=null){
                sb.append(temp);
                temp=br.readLine();
            }
            
            return DES2.decodeValue(Global.DES_KEY, sb.toString());
            
        } catch (IOException ex) {
            return content;
        }   
    }

    public boolean writeFile(String filename,String message)
    {

        String fname = filename+".txt";
        File file = new File("iccid//"+fname);
        if(!file.exists()||file.isDirectory())
        {
            try {
                file.createNewFile();
            } catch (IOException ex) {
               return false;
            }
        }
        try {
            PrintWriter pw = new PrintWriter(new FileWriter(file), true);
            pw.println(DES2.encode(Global.DES_KEY, message));
            pw.close();
        } catch (Exception ex) {
            return false;
        }
        return true;
    }

    public int getCount()
    {
         File file = new File(filedir);
         return file.listFiles().length;
    }

    public boolean isExitFile(String iccid)
    {
        String filename = iccid+".txt";
        File file = new File("iccid//"+filename);
        if(file.exists()&&file.isFile())
        {
            return true;
        }
        return false;
    }

}
